package com.adnaan.boot.runner;

import com.adnaan.boot.config.SystemInfoConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.util.Arrays;

/**
 * 应用程序启动完成后运行，显示系统配置信息
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AppStartupRunner implements CommandLineRunner {

    private final Environment env;
    private final SystemInfoConfig systemInfo;

    @Value("${server.port:8080}")
    private String serverPort;

    @Value("${server.servlet.context-path:/}")
    private String contextPath;

    @Value("${spring.application.name:Adnaan}")
    private String applicationName;

    @Override
    public void run(String... args) throws Exception {
        String ip = InetAddress.getLocalHost().getHostAddress();
        String activeProfiles = Arrays.toString(env.getActiveProfiles());
        activeProfiles = activeProfiles.equals("[]") ? "default" : activeProfiles;

        log.info("\n----------------------------------------------------------\n" +
                        "\t应用 '{}' 启动成功!\n" +
                        "\t系统信息: \t{}\n" +
                        "\t描述: \t\t{}\n" +
                        "\t环境: \t\t{}\n" +
                        "\t启动时间: \t{}\n" +
                        "----------------------------------------------------------\n",
                applicationName,
                systemInfo.getFullInfo(),
                systemInfo.getDescription(),
                activeProfiles,
                systemInfo.getStartTime());

        String druidUserName = env.getProperty("spring.datasource.druid.stat-view-servlet.login-username");
        String druidPassword = env.getProperty("spring.datasource.druid.stat-view-servlet.login-password");

        log.info("\n----------------------------------------------------------\n" +
                        "\t访问地址:\n" +
                        "\t本地地址: \thttp://localhost:{}{}\n" +
                        "\t外部地址: \thttp://{}:{}{}\n" +
                        "\t文档地址: \thttp://localhost:{}{}/doc.html\n" +
                        "\tSwagger UI: \thttp://localhost:{}{}/swagger-ui/index.html\n" +
                        "\tDruid监控: \thttp://localhost:{}{}/druid/index.html druidUserName:{} druidPassword:{}\n" +
                        "----------------------------------------------------------\n",
                serverPort, formatContextPath(contextPath),
                ip, serverPort, formatContextPath(contextPath),
                serverPort, formatContextPath(contextPath),
                serverPort, formatContextPath(contextPath),
                serverPort, formatContextPath(contextPath),druidUserName,druidPassword);

        // 打印数据库配置信息
        printDatabaseInfo();

        // 打印Redis配置信息
        printRedisInfo();

        // 打印Sa-Token配置信息
        printSaTokenInfo();
    }

    /**
     * 打印数据库配置信息
     */
    private void printDatabaseInfo() {
        String jdbcUrl = env.getProperty("spring.datasource.url");
        String username = env.getProperty("spring.datasource.username");
        String type = env.getProperty("spring.datasource.type");

        log.info("\n----------------------------------------------------------\n" +
                        "\t数据库配置信息:\n" +
                        "\t类型: \t\t{}\n" +
                        "\t连接地址: \t{}\n" +
                        "\t用户名: \t{}\n" +
                        "----------------------------------------------------------\n",
                type,
                jdbcUrl,
                username);
    }

    /**
     * 打印Redis配置信息
     */
    private void printRedisInfo() {
        String redisHost = env.getProperty("spring.data.redis.host");
        String redisPort = env.getProperty("spring.data.redis.port");
        String redisDb = env.getProperty("spring.data.redis.database");

        if (redisHost != null && redisPort != null) {
            log.info("\n----------------------------------------------------------\n" +
                            "\tRedis配置信息:\n" +
                            "\t地址: \t\t{}:{}\n" +
                            "\t数据库: \t{}\n" +
                            "----------------------------------------------------------\n",
                    redisHost,
                    redisPort,
                    redisDb);
        }
    }

    /**
     * 打印Sa-Token配置信息
     */
    private void printSaTokenInfo() {
        String tokenName = env.getProperty("sa-token.token-name");
        String timeout = env.getProperty("sa-token.timeout");
        String tokenStyle = env.getProperty("sa-token.token-style");

        log.info("\n----------------------------------------------------------\n" +
                        "\tSa-Token配置信息:\n" +
                        "\tToken名称: \t{}\n" +
                        "\t有效期: \t{}秒\n" +
                        "\tToken风格: \t{}\n" +
                        "----------------------------------------------------------\n",
                tokenName,
                timeout,
                tokenStyle);
    }

    /**
     * 格式化上下文路径，确保以"/"开头但不以"/"结尾
     */
    private String formatContextPath(String path) {
        if (!path.startsWith("/")) {
            path = "/" + path;
        }
        if (path.equals("/")) {
            return "";
        }
        if (path.endsWith("/")) {
            path = path.substring(0, path.length() - 1);
        }
        return path;
    }
} 